﻿using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;

namespace YuRadio
{
    public class StationManager
    {
        static readonly string stationListFile = Path.Combine(Xamarin.Essentials.FileSystem.AppDataDirectory, "stations.dat");
        public static void Add(Station station)
        {
            var list = GetList();
            list.Add(station);
            saveStations(list);
        }

        //查看本地是否有文件stations.dat，如果没有则创建
        static void CheckLocalStationStore()
        {
            if (!File.Exists(stationListFile))
            {
                var stations = getDefaultStations();
                saveStations(stations);
            }
        }

        internal static void saveStations(List<Station> stations)
        {
            var stream = File.Open(stationListFile, FileMode.OpenOrCreate);
            BinaryFormatter formatter = new BinaryFormatter();
            formatter.Serialize(stream, stations);
            stream.Close();
        }


        internal static List<Station> GetList()
        {
            CheckLocalStationStore();
            var stream = File.OpenRead(stationListFile);
            BinaryFormatter formatter = new BinaryFormatter();
            List<Station> stations = (List<Station>)formatter.Deserialize(stream);
            stream.Close();
            return stations;
        }

        static List<Station> getDefaultStations()
        {
            var list = new List<Station>() {
                new Station{ Icon="", Name="经济之声", Url="http://lhttp.qingting.fm/live/387/64k.mp3" },
                new Station{ Icon="", Name="音乐之声", Url="http://lhttp.qingting.fm/live/388/64k.mp3" },
                new Station{ Icon="", Name="中国之声", Url="http://lhttp.qingting.fm/live/390/64k.mp3" },
                new Station{ Icon="", Name="华夏之声", Url="http://lhttp.qingting.fm/live/389/64k.mp3" },
                new Station{ Icon="", Name="CKNW AM", Url="http://live.leanstream.co/CKNWAM" },
                new Station{ Icon="", Name="CBC Radio One", Url="https://cbcliveradio-lh.akamaihd.net/i/CBCR1_VCR@314572/master.m3u8" },
                new Station{ Icon="", Name="News 1130", Url="https://rogers-hls.leanstream.co/rogers/van1130.stream/playlist.m3u8" },
                new Station{ Icon="", Name="CHQT iNews 880", Url="http://live.leanstream.co/CHQTAM" }
            };
            return list;
        }

    }
}